package com.thoughtworks.impersonator.http.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class MD5 {

    private static MessageDigest md = null;
    private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
            'F'};
    public static final int HASH_LENGTH = 32;

    static {
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (final NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String hashData(final String dataToHash) {
        return hashData(dataToHash.getBytes());
    }

    public static String hashData(final byte[] dataToHash) {
        return stringFromBytes(calculateHash(dataToHash));
    }

    private static byte[] calculateHash(final byte[] dataToHash) {
        md.update(dataToHash, 0, dataToHash.length);
        return (md.digest());
    }

    private static String stringFromBytes(final byte[] b) {
        final StringBuilder hex = new StringBuilder();
        int msb;
        int lsb = 0;
        // MSB maps to idx 0
        for (int i = 0; i < b.length; i++) {
            msb = (b[i] & 0x000000FF) / 16;
            lsb = (b[i] & 0x000000FF) % 16;
            hex.append(HEX_CHARS[msb]);
            hex.append(HEX_CHARS[lsb]);
        }
        return (hex.toString());
    }

}
